package com.hspedu.hspliving.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.hspedu.hspliving.commodity.dao.AttrAttrgroupRelationDao;
import com.hspedu.hspliving.commodity.dao.AttrgroupDao;
import com.hspedu.hspliving.commodity.entity.AttrAttrgroupRelationEntity;
import com.hspedu.hspliving.commodity.entity.AttrgroupEntity;
import com.hspedu.hspliving.commodity.service.AttrAttrgroupRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.common.utils.PageUtils;
import com.hspedu.common.utils.Query;

import com.hspedu.hspliving.commodity.dao.AttrDao;
import com.hspedu.hspliving.commodity.entity.AttrEntity;
import com.hspedu.hspliving.commodity.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Resource
    private AttrgroupDao attrgroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getAllowRelationAttr(Map<String, Object> params, Long attrgroupId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();

        //获取可关联的基本属性
        //找到该属性组的分类下所有属性组
        Long categoryId = attrgroupDao.selectById(attrgroupId).getCategoryId();
        List<AttrgroupEntity> attrgroupEntities = attrgroupDao.selectList(
                new QueryWrapper<AttrgroupEntity>().eq("category_id", categoryId));
        List<Long> groupIds = attrgroupEntities.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = attrgroupRelationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //查询没有关联的同分类的属性
        wrapper.eq("category_id", categoryId).eq("attr_type",1);
        if(!attrIds.isEmpty()){
            wrapper.notIn("attr_id", attrIds);
        }

        //处理查询的条件
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params,Long categoryId) {
        //获取关键字
        String key = (String)params.get("key");
        QueryWrapper<AttrEntity> Wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",1);

        if (categoryId != 0) {//如果为 0, 表示不将 categoryId 作为查询条件
            Wrapper.eq("category_id", categoryId);
        }

        //封装查询条件
        if(StringUtils.isNotBlank(key)){
//            Wrapper.eq("id",key).or().like("name",key);
            Wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                Wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils querySalePage(Map<String, Object> params, Long categoryId) {
        //获取关键字
        String key = (String)params.get("key");
        QueryWrapper<AttrEntity> Wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",0);

        if (categoryId != 0) {//如果为 0, 表示不将 categoryId 作为查询条件
            Wrapper.eq("category_id", categoryId);
        }

        //封装查询条件
        if(StringUtils.isNotBlank(key)){
//            Wrapper.eq("id",key).or().like("name",key);
            Wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                Wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttrAndRelation(AttrEntity attr) {
        this.save(attr);

        //保存属性和组关系
        if(attr.getAttrType() == 1 && attr.getAttrGroupId() != null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Transactional
    @Override
    public void removeAndRelation(Long[] attrIds) {
        for (Long attrId : attrIds) {
            this.removeById(attrId);
            relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        }
    }

    @Override
    public List<AttrEntity> getAttrByAttrGroupId(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = attrgroupRelationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //如果没有关联的属性，返回 null
        if(attrIds == null || attrIds.size() == 0){
            return null;
        }

        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteAttrRelationBatch(List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities) {
        relationDao.deleteAttrRelationBatch(attrAttrgroupRelationEntities);
    }
}
